﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using EasierRdp.Base;
using EasierRdp.Util;

namespace EasierRdp.Models
{
    class RdpGroup : RdpModel, IGroupContainer
    {
        private IList<RdpGroup> _groups = new List<RdpGroup>();
        private IList<RdpUser> _users = new List<RdpUser>();
        private IList<RdpServer> _servers = new List<RdpServer>();

        public const string ElementName = "Group";
        public IList<RdpGroup> Groups { get { return _groups; } }
        public IList<RdpUser> Users { get { return _users; } }
        public IList<RdpServer> Servers { get { return _servers; } }

        public override IEnumerable<INode> Children
        {
            get
            {
                foreach (var item in _groups)
                {
                    yield return item;
                }
                foreach (var item in _users)
                {
                    yield return item;
                }
                foreach (var item in _servers)
                {
                    yield return item;
                }
            }
        }

        public RdpGroup(string name)
        {
            Name = name;
        }

        public RdpGroup(XElement element)
        {
            if (element != null)
            {
                Name = element.GetString(AttributeName);
                _users.FromXml(element, RdpUserRef.ElementName);
                _servers.FromXml(element, RdpServerRef.ElementName);
                _groups.FromXml(element, RdpGroup.ElementName);
                Expanded = element.GetBoolean(AttributeExpanded);
                return;
            }
            throw new ArgumentNullException("element");
        }

        public override XElement ToXml()
        {
            return new XElement(ElementName, new XAttribute(AttributeExpanded, Expanded), new XAttribute(AttributeName, Name), _groups.ToXml(), _servers.ToXml(), _users.ToXml());
        }

        public RdpGroup Clone()
        {
            var ret = (RdpGroup)MemberwiseClone();
            ret.Clear();
            return ret;
        }

        private void Clear()
        {
            _groups = new List<RdpGroup>();
            _users = new List<RdpUser>();
            _servers = new List<RdpServer>();
        }
    }

    static class RdpGroupExtension
    {
        public static IEnumerable<XElement> ToXml(this IEnumerable<RdpGroup> src)
        {
            return src == null ? null : src.Select(s => s.ToXml());
        }

        public static void FromXml(this IList<RdpGroup> src, XElement parentElement, string elementName)
        {
            foreach (var item in parentElement.Elements(elementName).Select(e => new RdpGroup(e)))
            {
                src.Add(item);
            }
        }
    }
}
